import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Stack;

public class Solution103 {
    List<List<Integer>> res;

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        zigzagLevel(stack, true);
        return res;
    }

    private void zigzagLevel(Stack<TreeNode> stack, boolean isRight) {
        if (stack.empty()) {
            return;
        }
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> nextLevel = new Stack<>();
        while (!stack.empty()) {
            TreeNode t = stack.pop();
            list.add(t.val);
            if (isRight) {
                if (t.left != null) {
                    nextLevel.push(t.left);
                }
                if (t.right != null) {
                    nextLevel.push(t.right);
                }
            } else {
                if (t.right != null) {
                    nextLevel.push(t.right);
                }
                if (t.left != null) {
                    nextLevel.push(t.left);
                }
            }
        }
        res.add(new ArrayList<>(list));
        Collections.reverse(list);
        zigzagLevel(nextLevel, !isRight);
    }
}
